<template>
  <view>
    <view v-if="!pickerItem.isRange" @click="clickPicker(pickerItem)" class="picker">
      <view v-if="pickerFormData[pickerItem.key].value" class="value">
        {{ pickerFormData[pickerItem.key].value }}
        <uni-icons
          class="picker-clear"
          type="clear"
          color="c0c4cc"
          size="40rpx"
          @click.stop="clickClearIcon(pickerItem)"
        ></uni-icons>
      </view>
      <view v-else class="placeholder">
        {{ pickerItem.placeholder || '请选择' + pickerItem.label }}
        <uni-icons
          class="forward-icon"
          type="forward"
          color="#999"
          size="14"
        ></uni-icons>
      </view>
      <slot name="right"></slot>
    </view>
    <view v-else class="value-list">
      <view class="first-item" @click="clickFirstPicker(pickerItem)">
        <view v-if="pickerFormData[pickerItem.key].value[0]" class="value">
          {{ pickerFormData[pickerItem.key].value[0] }}
          <uni-icons
            class="picker-clear"
            type="clear"
            color="c0c4cc"
            size="40rpx"
            @click.stop="clickClearIcon(pickerItem, 0)"
          ></uni-icons>
        </view>
        <view v-else class="placeholder">
          {{ pickerItem.firstPlaceholder || '开始时间' }}
        </view>
      </view>
      <view class="link-line"></view>
      <view class="second-item" @click="clickSecondPicker(pickerItem)">
        <view v-if="pickerFormData[pickerItem.key].value[1]" class="value">
          {{ pickerFormData[pickerItem.key].value[1] }}
          <uni-icons
            class="picker-clear"
            type="clear"
            color="c0c4cc"
            size="40rpx"
            @click.stop="clickClearIcon(pickerItem, 1)"
          ></uni-icons>
        </view>
        <view v-else class="placeholder">
          {{ pickerItem.secondPlaceholder || '结束时间' }}
        </view>
      </view>
      <slot name="right"></slot>
    </view>
    <u-picker
      :show="showPicker"
      ref="uPicker"
      :columns="pickerOptions"
      :defaultIndex="[0, 0, 0]"
      keyName="text"
      :closeOnClickOverlay="true"
      @change="changeHandler"
      @confirm="confirmTimePicker"
      @close="closeTimePicker"
      @cancel="closeTimePicker"
    ></u-picker>
  </view>
</template>

<script>
  import { TIME_CONFIG } from '../formConfig/timeConfig'
  export default {
    name: 'pickerForm',
    data() {
      return {
        showPicker: false,
        pickerOptions: [],
        column2Data: [],
        column3Data: [],
        selectPopupKey: '',
        selectIndex: 0,
        pickerFormData: {},
        newArr: {},
        valueData: null,
        dataForm: {},
        pickerItem: {}
      }
    },
    props: {
      pickerForm: {
        type: Object
      },
      item: {
        type: Object
      },
      localData: {
        type: Object,
        default() {
          return {}
        }
      }
    },
    watch: {
      pickerForm: {
        handler(newVal, oldVal) {
          if (newVal[this.pickerItem.key]) {
            this.getPickerFormData()
          }
        },
        deep: true
      },
      item: {
        handler(newVal, oldVal) {
          this.pickerItem = newVal
        },
        deep: true,
        immediate: true
      },
      localData: {
        immediate: true,
        deep: true,
        handler(newVal, oldVal) {
          this.pickerItem.options = newVal[this.pickerItem.key]
          if (this.pickerForm[this.pickerItem.key]) {
            this.getPickerFormData()
          }
        }
      }
    },
    created() {
    },
    methods: {
      getPickerFormData() {
        if (this.pickerItem.isRange) {
          const pickerArr = this.pickerForm[this.pickerItem.key].split('-')
          this.pickerFormData[this.pickerItem.key] = {
            value: [pickerArr[0], pickerArr[1]]
          }
        } else {
          this.getFormData()
        }
      },
      getFormData() {
        if (!this.pickerItem.options) return
        this.pickerFormData = {
          [this.pickerItem.key]: {
            value: this.recursionData(this.pickerForm[this.pickerItem.key], this.pickerItem.options).join('/')
          }
        }
      },
      recursionData(dataArr, options, arr) {
        let labelArr = arr || []
        options.forEach(item => {
          if (dataArr.includes(item.value)) {
            labelArr.push(item.text)
          }
          if (item.children && item.children.length) {
            this.recursionData(dataArr, item.children, labelArr)
          }
        })
        return labelArr
      },
      changeHandler(e) {
        const {
          columnIndex,
          index,
          indexs,
          // 微信小程序无法将picker实例传出来，只能通过ref操作
          picker = this.$refs.uPicker
        } = e
        // 当第一列值发生变化时，变化第二列(后一列)对应的选项
        if (columnIndex === 0) {
          // picker为选择器this实例，变化第二列对应的选项
          picker.setColumnValues(1, this.column2Data[index])
          // 变化第三列对应的选项
          picker.setColumnValues(2, this.column3Data[index][indexs[1]])
        }
        if (columnIndex === 1) {
          // picker为选择器this实例，变化第三列对应的选项
          picker.setColumnValues(2, this.column3Data[indexs[0]][index])
        }
      },
      clickPicker(item) {
        this.getOptions(item)
      },
      clickFirstPicker(item) {
        this.selectIndex = 0
        this.getOptions(item)
      },
      clickSecondPicker(item) {
        this.selectIndex = 1
        this.getOptions(item)
      },
      getOptions(item) {
        if (!(item.options && item.options.length)) return
        this.pickerFormData[item.key] = this.pickerFormData[item.key] || {}
        if (item.isTime) {
          this.pickerOptions = [...TIME_CONFIG ]
        } else {
          const column1Data = item.options.map(item => {
            return { text: item.text, value: item.value }
          })
          const dataLength = this.handleOptions(item.options)
          let options = []
          if (dataLength > 1) {
            this.column2Data = this.handleColumnData(item.options, '2')
            options = [column1Data, this.column2Data[0]]
          }
          if (dataLength > 2) {
            this.column3Data = this.handleColumnData(item.options, '3')
            options = [column1Data, this.column2Data[0], this.column3Data[0][0]]
          }
          this.pickerOptions = options || []
        }
        this.selectPopupKey = item.key
        this.showPicker = true
        this.$emit('setPickerForm', this.pickerFormData)
      },
      handleOptions(options) {
        let dataLength = 1
        options.forEach(item => {
          if (item.children) {
            dataLength = 2
            item.children.forEach(cItem => {
              if (cItem.children) dataLength = 3
            })
          }
        })
        return dataLength
      },
      handleColumnData(options, num) {
        let thirdData = {}
        let secondData = {}
        let newData = null
        options.forEach((item, index) => {
          if (num === '2') {
            if (!(item.children && item.children.length)) {
              secondData[index] = []
            }
            secondData[index] = item.children.map(cItem => {
              return { text: cItem.text, value: cItem.value }
            })
            newData = secondData
          }
          if (num === '3') {
            thirdData[index] = {}
            item.children.forEach((ccItem, ccIndex) => {
              if (!(ccItem.children && ccItem.children.length)) {
                thirdData[index][ccIndex] = []
              } else {
                thirdData[index][ccIndex] = ccItem.children && ccItem.children.map(cItem => {
                  return { text: cItem.text, value: cItem.value }
                })
              }
              newData = thirdData
            })
          }
        })
        return newData
      },
      clickClearIcon(item, index) {
        this.pickerOptions = []
        if (this.item.isRange) {
          this.pickerFormData[item.key].value[index] = ''
        } else {
          this.pickerFormData[item.key].value = ''
        }
        this.$emit('setPickerForm', this.pickerFormData)
      },
      confirmTimePicker($event) {
        this.showPicker = false
        let resValue = ''
        let valueData = ''
        if ($event.value instanceof Array) {
          const value = $event.value.filter(item => item !== undefined)
          resValue = value.map(item => item.text).join(this.pickerItem.isTime ? ':' : this.pickerItem.splitIcon || '/')
          valueData = value.map(item => item.value).join(this.pickerItem.isTime ? ':' : this.pickerItem.splitIcon || '/')
          this.pickerForm[this.selectPopupKey] = value.map(item => item.value)
          this.getPickerFormData()
        } else {
          resValue = $event.value.join(this.pickerItem.isTime ? ':' : this.pickerItem.splitIcon || '/')
        }
        let pickerFormData = {}
        if (this.pickerItem.isRange) {
          pickerFormData = {
            [this.selectPopupKey]: {
              value: this.pickerFormData[this.selectPopupKey].value || []
            }
          }
          pickerFormData[this.selectPopupKey].value[this.selectIndex] = resValue
        } else {
          pickerFormData = {
            [this.selectPopupKey]: {
              value: resValue
            }
          }
          if ($event.value instanceof Array) {
            pickerFormData = {
              [this.selectPopupKey]: {
                valueKey: this.pickerItem.key,
                labelKey: this.pickerItem.labelKey,
                [this.pickerItem.key]: valueData,
                [this.pickerItem.labelKey]: resValue
              }
            }
          }
        }
        
        this.$emit('setPickerForm', pickerFormData)
      },
      closeTimePicker() {
        this.showPicker = false
      }
    }
  }
</script>

<style lang="scss" scoped>
  .value {
    display: flex;
    align-items: center;
    margin-right: -40rpx;
    .picker-clear {
      margin-left: 6rpx;
    }
  }
  .placeholder {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    // padding-right: 16rpx;
    color: #ccc;
    .forward-icon {
      margin-left: 8rpx;
    }
  }
  ::v-deep.picker {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
  }
  .value-list {
    display: flex;
    align-items: center;
    .value {
      margin-right: -20rpx;
    }
    .link-line {
      width: 20rpx;
      height: 4rpx;
      margin-right: 14rpx;
      border-radius: 4rpx;
      background-color: #a8a8a8;
    }
  }
</style>